package com.njtoyo.taxi.admin.library.payment.wechat;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.njtoyo.taxi.admin.library.payment.common.PayBasicInfo;
import com.taxi.util.General;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import weixin.popular.api.PayMchAPI;
import weixin.popular.bean.paymch.SecapiPayRefund;
import weixin.popular.bean.paymch.SecapiPayRefundResult;
import weixin.popular.client.LocalHttpClient;

import javax.annotation.PostConstruct;
import java.util.Objects;

/**
 * @Author Dell
 * @Date 2021/5/31 16:07
 */
@Component
@Slf4j
public class WxPayClient {

    @Autowired
    private WxPayConfig wxPayConfig;

    @PostConstruct
    public void init() {
        if (!FileUtil.exist(wxPayConfig.getCertPath())) {
            log.info("找不到指定支付文件");
            return;
        }
        LocalHttpClient.initMchKeyStore(wxPayConfig.getMchId(), wxPayConfig.getCertPath());
    }

    public SecapiPayRefundResult refund(PayBasicInfo payBasicInfo) {
        SecapiPayRefund refund = buildRefund(payBasicInfo);
        SecapiPayRefundResult result = PayMchAPI.secapiPayRefund(refund, wxPayConfig.getMchKey());
        return result;
    }

    private SecapiPayRefund buildRefund(PayBasicInfo payBasicInfo) {
        SecapiPayRefund refund = new SecapiPayRefund();

        if (Objects.nonNull(payBasicInfo.getWxAppType())) {
            switch (payBasicInfo.getWxAppType()) {
                case wxapp:
                    refund.setAppid(wxPayConfig.getAppId());
                    break;
                case wxmina:
                    refund.setAppid(wxPayConfig.getMiniappId());
                    break;
                default:
                    break;
            }
        }

        String nonceStr = IdUtil.simpleUUID();

        refund.setMch_id(wxPayConfig.getMchId());
        refund.setNonce_str(nonceStr);
        refund.setTransaction_id(payBasicInfo.getOutTradeNo());
        refund.setOut_trade_no(payBasicInfo.getNumber());
        refund.setOut_refund_no(payBasicInfo.getRufundNo());
        refund.setTotal_fee(General.wxPayConvert(payBasicInfo.getAmount()).intValue());
        refund.setRefund_fee(General.wxPayConvert(payBasicInfo.getRefundAmount()).intValue());
        refund.setSign_type("MD5");
        return refund;
    }

}
